package com.ucombuy.search.controller;

import com.alibaba.fastjson.JSON;
import com.ucombuy.search.client.SponsorClient;
import com.ucombuy.search.client.vo.AdPlan;
import com.ucombuy.search.client.vo.AdPlanGetRequest;
import com.ucombuy.search.search.ISearch;
import com.ucombuy.search.search.vo.SearchRequest;
import com.ucombuy.search.search.vo.SearchResponse;
import com.ucombuy.search.utils.CommonUtils;
import com.uocmbuy.adver.common.annotation.IgnoreResponseAdvice;
import com.uocmbuy.adver.common.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by yaosheng on 2021/3/29.
 */
@Slf4j
@RestController
public class SearchController {

    private final ISearch iSearch;
    private final RestTemplate restTemplate;
    private final SponsorClient sponsorClient;

    @Autowired
    public SearchController(RestTemplate restTemplate, SponsorClient sponsorClient,ISearch iSearch) {
        this.restTemplate = restTemplate;
        this.sponsorClient = sponsorClient;
        this.iSearch = iSearch;
    }

    /**
     * 广告检索服务统一接口
     */
    @PostMapping("/fetchAds")
    public SearchResponse fetchAds(@RequestBody SearchRequest request){
        log.info ("Ad-search: fetches -> {}",JSON.toJSONString (request));
        return iSearch.fetchAds (request);
    }

    /**
     * 使用Feign + Hystrix实现微服务的统一调用加熔断升级
     */
    @IgnoreResponseAdvice
    @PostMapping("/getAdPlans")
    public CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request) {
        log.info("Ad-search: getAdPlans -> {}", JSON.toJSONString(request));
        return sponsorClient.getAdPlans(request);
    }

    /**
     * 使用Ribbon，通过Eureka服务调用获取推广计划接口
     */
    @SuppressWarnings("all")
    @IgnoreResponseAdvice
    @PostMapping("/getAdPlansByRibbon")
    public CommonResponse<List<AdPlan>> getAdPlansByRebbon(@RequestBody AdPlanGetRequest request) {
        log.info("Ad-search: getAdPlansByRibbon -> {}", JSON.toJSONString (request));
        return restTemplate.postForEntity("http://eureka-client-ad-sponsor/ad-sponsor/get/adPlan",
                request, CommonResponse.class).getBody();
    }
}
